import Vue from 'vue'
import { Toast } from 'cube-ui'
Vue.use(Toast)
import md5 from 'js-md5'

export const addCss = (href) => {
    const oldLink = document.getElementsByTagName('link')
    for (var i = oldLink.length; i >= 0; i--) {
        if (oldLink[i] && oldLink[i].getAttribute('href') != null && oldLink[i].getAttribute('href').indexOf(href) !== -1) {
            oldLink[i].parentNode.removeChild(oldLink[i])
        }
    }

    const link = document.createElement('link')
    link.setAttribute('rel', 'stylesheet')
    link.setAttribute('type', 'text/css')
    link.setAttribute('href', href)
    document.getElementsByTagName('head')[0].appendChild(link)
}

export const removeCss = (href) => {
    const link = document.getElementsByTagName('link')
    for (var i = link.length; i >= 0; i--) {
        if (link[i] && link[i].getAttribute('href') != null && link[i].getAttribute('href').indexOf(href) !== -1) {
            link[i].parentNode.removeChild(link[i])
        }
    }
}

export const show = (msg = 'OK', type = 'text') => {
    const toast = Toast.$create({
        txt: type == 'loading' ? '加载中。。。' : msg,
        type: type,
        mask: false
    }, false);

    toast.show();
    return toast;
}

export const getSign = data => {
    const arr = sort_ascii(data);

    let sign = "";
    for (var i = 0, size = arr.length; i < size; i++) {
        if(arr[i] != 'sign') {
            sign += arr[i] + "=" + (data[arr[i]] instanceof Object ? JSON.stringify(data[arr[i]]) : data[arr[i]]) + "&"
        }
    }
    sign = sign.substring(0, sign.length - 1);
    console.info(sign)
    return hex_md5(sign)
}

export const hex_md5 = str => {
    return md5(str);
}

export const sort_ascii = data => {
    var arr = new Array();
    var num = 0;
    for (var i in data) {
        arr[num] = i;
        num++;
    }
    return arr.sort();
}


export const findIndex = (ary, fn) => {
    if (ary.findIndex) {
        return ary.findIndex(fn);
    }
    let index = -1;
    ary.some(function (item, i, ary) {
        const ret = fn.call(this, item, i, ary);
        if (ret) {
            index = i;
            return ret;
        }
    });
    return index;
};